﻿using FineUI;
using System;
using System.Data;
using System.Linq;
using ZHDJ.Core;
using ZHDJ.Core.Util;
using ZHDJ.Data.BLL;
using ZHDJ.Data.Models.Center;
using ZHDJ.Data.Models.Common;
using ZHDJ.Data.Models.JoinParty;
using ZHDJ.Data.Models.Org;
using ZHDJ.PersonalCenter.BLL;
using ZHDJ.WebPage;

namespace ZHDJ.PersonalCenter.Module.RelationshipTransfer
{
    public partial class RelationshipTransferFrom : PageBase
    {
        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "";
            }
        }

        public string mode
        {
            get
            {
                return this.Request["mode"] ?? "";
            }
        }
        #endregion

        #region Page_Load
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckLoginWithSymbol(true, true);
            DataSet ds = PartyRelationshipTransfer.GetApplying(this.CurrentUser.LoginID);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                //已存在一条审批中的数据  转到记录表单
                Response.Redirect(WebHost + "/App/PersonalCenter/Module/RelationshipTransfer/RelationshipTransferView.aspx?RelationID=" + ds.Tables[0].Rows[0]["ID"] + "&mode=" + mode);
            }
            if (!string.IsNullOrEmpty(this.mode))
            {
                //this.divContent.Attributes["style"] = "overflow-y:auto;height:600px";
            }

            if (!IsPostBack)
            {
                //if (!string.IsNullOrEmpty(this.CurrentUser.LoginID))
                //{
                //    string applyParty = PartyJoinApplycation.GetApplyIDByLoginID(this.CurrentUser.LoginID);

                //    //if (!PartyOrgMember.CheckRunSate(this.CurrentUser.LoginID) && string.IsNullOrEmpty(applyParty))
                //    if (!string.IsNullOrEmpty(applyParty))
                //    {
                //        RedirectTo("default", "~/default.aspx");
                //    }
                //}
                this.BindData();
                this.LoadData();
            }
        }

        private void BindData()
        {
            ControlBusiness.ControlBindDataDictionary(ddlPoliticsLineament, SysDataDictionary.MemberPoliticsLineamentKey);
            ControlBusiness.ControlBindDataDictionary(ddlType, SysDataDictionary.RelationshipTransferFormType);
        }

        private void LoadData()
        {
            PartyOrgMember member = DB.PartyOrgMembers.Find(this.CurrentUser.LoginID);
            this.txtAge.Text = "";
            this.txtApplicant.Text = member.UserName;
            this.txtIDCard.Text = member.IdentityCard;
            this.txtMobileNo.Text = member.MobileNo;
            this.txtNation.Text = member.Nation;
            //this.txtSerialNumber.Text = PartyRelationshipTransfer.GetSerialNumber();
            this.ddlPoliticsLineament.SelectedValue = member.PoliticsLineament;
            this.ppBranch.Value = member.BranchID;
            this.ppBranch.Text = ControlBusiness.GetBranchPickerText(member.BranchID);

            if (string.IsNullOrEmpty(member.BranchID))
            {
                this.txtToIn.Text = member.WorkUnit;
            }
            if (string.IsNullOrEmpty(member.BranchID) || member.runSate != "0")
            {
                this.ddlType.SelectedValue = "2";
                this.ddlType.Enabled = false;
                PageContext.RegisterStartupScript("$('#trhost').show();$('#trOut').hide();$('#trfrom').hide();$('#trIn').show();");
            }

            this.dtMemberCost.Text = PartyRelationshipTransfer.GetMemberCostDate(this.CurrentUser.LoginID);
            this.radGrean.SelectedValue = member.Gender;
        }

        public bool CheckValue()
        {

            var rs = true;

            if (this.txtAge.Text.Trim() == "")
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('请输入年龄');", true);
                rs = false;
            }

            if (!ValidateHelper.IsInt(this.txtAge.Text.Trim()))
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('年龄为数字');", true);
                rs = false;
            }
            if (this.txtFromBranchFax.Text.Trim() == "")
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('请输入所属组织传真');", true);
                rs = false;
            }
            if (this.txtFromBranchZip.Text.Trim() == "")
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('请输入所属组织邮编');", true);
                rs = false;
            }
            if (this.txtFromBranchMobileNo.Text.Trim() == "")
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('请输入所属组织联系电话');", true);
                rs = false;
            }

            if (this.ddlType.SelectedValue == "0")
            {
                if (this.ppTargetBranch.Value.Trim() == "")
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('请选择目标组织');", true);
                    rs = false;
                }
                if (this.ppBranch.Value.Trim() == "")
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('区内转移时，所属组织不能为空！');", true);
                    rs = false;
                }
            }
            if (this.ddlType.SelectedValue == "1")
            {
                if (this.txtToOut.Text.Trim() == "")
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('请输入目标组织');", true);
                    rs = false;
                }
                if (this.ppBranch.Value.Trim() == "")
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('向外区转移时，所属组织不能为空！');", true);
                    rs = false;
                }
            }
            if (this.ddlType.SelectedValue == "2")
            {
                if (this.ppTargetBranch.Value.Trim() == "")
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('请选择目标组织');", true);
                    rs = false;
                }
                if (this.txtToIn.Text.Trim() == "")
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('请输入所属组织');", true);
                    rs = false;
                }
            }
            return rs;
        }

        #endregion

        #region Events
        /// <summary>
        /// 确认按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            if (!CheckValue())
            {
                return;
            }
            if (PartyRelationshipTransfer.GetApplying(this.CurrentUser.LoginID).Tables[0].Rows.Count > 0)
            {
                //Alert.Show("你已经申请了一次组织关系转移,不能重复申请！");
                this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('你已经申请了一次组织关系转移,不能重复申请！');UrlRefresh('" + WebHost + "/app/PersonalMain.aspx');", true);

                return;
            }
            /**
             2016-10-10
            客户要求取消自动生成编号，改为自己填写
            郭 
             */
            //if (PartyRelationshipTransfer.CheckSerialNumber(this.txtSerialNumber.Text.Trim()))
            //{
            //    this.txtSerialNumber.Text = PartyRelationshipTransfer.GetSerialNumber();
            //    //Alert.Show(string.Format("已存在相同的编号，编号重新生成，新编号为：{0}'，请悉知！", this.txtSerialNumber.Text));
            //    this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('" + string.Format("已存在相同的编号，编号重新生成，新编号为：{0}'，请悉知！", this.txtSerialNumber.Text) + "');", true);

            //    return;
            //}

            PartyOrgMember member = DB.PartyOrgMembers.Find(this.CurrentUser.LoginID);
            if (member.BranchID == ppTargetBranch.Value)
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('不能在同一组织内进行转移，请悉知！');", true);

                return;
            }

            //区外转区内
            var fromBranchID = "";

            PartyRelationshipTransfer transfer = new PartyRelationshipTransfer();
            transfer.ID = StringHelper.NewID;
            transfer.Explain = txtExplain.Text.Trim();
            transfer.TageBranchID = ppTargetBranch.Value;
            transfer.Applicant = this.CurrentUser.LoginID;
            transfer.CreateTime = DateTime.Now;
            transfer.Status = "审批中";
            if (ddlType.SelectedValue == "2")
            {
                transfer.FormerBranchID = this.txtToIn.Text;

                fromBranchID = "D658070EC3BF425BA8417745FDCBFCB0";//山海天ID
            }
            else
            {
                transfer.FormerBranchID = this.ppBranch.Value;
                fromBranchID = this.ppBranch.Value;
            }

            transfer.Age = Convert.ToInt32(this.txtAge.Text);
            transfer.FromBranchAddress = this.txtFromBranchAddress.Text;
            transfer.FromBranchFax = this.txtFromBranchFax.Text;
            transfer.FromBranchMobileNo = this.txtFromBranchMobileNo.Text;
            transfer.MemberCostTime = this.dtMemberCost.Text;
            transfer.FromBranchZip = this.txtFromBranchZip.Text;
            transfer.SerialNumber = this.txtSerialNumber.Text;
            transfer.ValidTime = 10;//有效期默认为10天
            transfer.Type = Convert.ToInt32(ddlType.SelectedValue);
            DB.PartyRelationshipTransfers.Add(transfer);
            if (ddlType.SelectedValue == "1")
                transfer.TageBranchID = txtToOut.Text;
            DB.SaveChanges();

            PartyRelationshipTransfer.AddRelationshipBranch(transfer.ID, Convert.ToInt32(this.ddlType.SelectedValue));

            PartyRelationshipProcesses processe = new PartyRelationshipProcesses();
            processe.ID = StringHelper.NewID;
            processe.ApplyID = transfer.ID;
            processe.Approver = this.CurrentUser.LoginID;
            processe.Explain = txtExplain.Text.Trim();
            processe.ApprovalResult = "提交申请";
            processe.CreateTime = DateTime.Now;
            processe.StepInfo = "1";

            DB.PartyRelationshiptblProcessess.Add(processe);
            DB.SaveChanges();

            string[] approval = new string[] { fromBranchID };

            //组织
            PartyTaskHelper.AddTaskToBranch(transfer.ID, member.UserName + "组织关系转移申请", SysEnum.TaskCategory.RelationshipTransfer,
                this.CurrentUser.LoginID, approval,
                "../../../../App/PersonalCenter/Module/RelationshipTransfer/RelationshipTransferApproval.aspx?RelationID=" + transfer.ID);
            //Response.Redirect("http://" + Request.Url.Host + "/app/PersonalMain.aspx");
            //短信提醒
            //申请人
            string msgcontent = string.Format("{0}同志：你的组织关系转移申请已提交，办理状态可登录山海天党建信息平台查看。", member.UserName);
            SMSHelper.CreateSmsSendRecord(member.MobileNo, msgcontent, "组织关系转移申请");
            //代办人短信提醒
            var allLoginID = DB.PartyOrgMembers.Where(o => o.BranchID == fromBranchID && o.IsPartyWorker == true).ToList();

            //string[] allLoginID = pjle.ToDoHandleUserID.Split(',');

            msgcontent = "{0}同志：您有一个{1}的组织关系转移申请需处理，请您登录山海天党建信息平台处理。";
            foreach (var item in allLoginID)
            {
                SMSHelper.CreateSmsSendRecord(item.MobileNo, string.Format(msgcontent, item.UserName, member.UserName), "组织关系转移申请处理");
            }

            this.ClientScript.RegisterStartupScript(this.GetType(), "kk", "alert('申请已提交，请耐心等待审核结果！');UrlRefresh('" + WebHost + "/app/PersonalMain.aspx');", true);
        }
        #endregion

        protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.ddlType.SelectedIndex == 1)
            {
                this.trhost.Style.Add("display", "none");
            }
            else
            {
                this.trOut.Style.Add("display", "none");
            }

            if (this.ddlType.SelectedIndex == 2)
            {
                this.trfrom.Style.Add("display", "none");
            }
            else
            {
                this.trIn.Style.Add("display", "none");
            }
        }
    }
}